package jlxy.ise.eroad.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.google.gson.Gson;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.json.JSONObject;

import cz.msebera.android.httpclient.Header;
import jlxy.ise.eroad.R;
import jlxy.ise.eroad.base.BaseSwitchFragment;
import jlxy.ise.eroad.bean.NlServerRps;
import jlxy.ise.eroad.bean.ServerRpsInfo;
import jlxy.ise.eroad.util.SingleToast;
import jlxy.ise.eroad.util.WebUtil;


/**
 * 结合定位SDK实现定位，并使用MyLocationOverlay绘制定位位置 同时展示如何使用自定义图标绘制并点击时弹出泡泡
 */
public class LocationFragment extends BaseSwitchFragment {

    // 定位相关
    private LocationClient mLocClient;
    public MyLocationListenner myListener = new MyLocationListenner();

    private MapView mMapView;
    private ImageView mImgUpLoad;
    private ImageView mImgLocate;
    private BaiduMap mBaiduMap;


    boolean isFirstLoc = true; // 是否首次定位

    private String lonStr = null;
    private  String latStr = null;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_location, container, false);
        // 地图初始化
        mMapView = (MapView) rootView.findViewById(R.id.bmapView);
        mImgUpLoad = (ImageView) rootView.findViewById(R.id.img_upload);
        mImgLocate = (ImageView) rootView.findViewById(R.id.img_locate);

        mImgLocate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //定位
                isFirstLoc = true;
                mLocClient.start();
            }
        });

        mImgUpLoad.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //上传位置信息

                if(TextUtils.isEmpty(lonStr)){
                    SingleToast.showToast(mAct, "请先获取定位位置", 2000);
                    return;
                }
                //上传位置信息
                WebUtil.postLocationAdd(WebUtil.getRpLocation(getDriverInfo().getId()+"",lonStr,latStr,System.currentTimeMillis()+""),new JsonHttpResponseHandler() {

                    @Override
                    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                        super.onSuccess(statusCode, headers, response);
                        Gson gson = new Gson();
                        try {
                            ServerRpsInfo serverRpsInfo = gson.fromJson(response.toString(), ServerRpsInfo.class);
                            if(serverRpsInfo.getStatus().equals("ok")&& serverRpsInfo.getMessage().equals("ok")) {
                                NlServerRps info = gson.fromJson(response.toString(), NlServerRps.class);
                                SingleToast.showToast(mAct, "上传位置信息成功", 2000);
                            }
                        } catch (Exception e) {
                            SingleToast.showToast(mAct, "上传位置信息出错:"+e.getLocalizedMessage(), 2000);
                        }
                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                        super.onFailure(statusCode, headers, throwable, errorResponse);
                        SingleToast.showToast(mAct, "上传位置信息失败", 2000);
                    }
                });

            }
        });
        initMap();
        return rootView;
    }


    private void initMap(){
        mBaiduMap = mMapView.getMap();
        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        // 定位初始化
        mLocClient = new LocationClient(mAct);
        mLocClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(1000);
        option.setIsNeedAddress(true);
        mLocClient.setLocOption(option);
        mLocClient.start();//开始定位

    }


    /**
     * 定位SDK监听函数
     */
    public class MyLocationListenner implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // map view 销毁后不在处理新接收的位置
            if (location == null || mMapView == null) {
                return;
            }
            lonStr = location.getLongitude()+"";
            latStr = location.getLatitude()+"";

            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                            // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(100).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            mBaiduMap.setMyLocationData(locData);
            if (isFirstLoc) {
                isFirstLoc = false;
                //移动到指定位置
                LatLng ll = new LatLng(location.getLatitude(),
                        location.getLongitude());
                MapStatus.Builder builder = new MapStatus.Builder();
                builder.target(ll).zoom(18.0f);
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
            }
        }

        @Override
        public void onConnectHotSpotMessage(String s, int i) {

        }

        public void onReceivePoi(BDLocation poiLocation) {
        }
    }

    @Override
    public void onPause() {
        mMapView.onPause();
        super.onPause();
    }

    @Override
    public void onResume() {
        mMapView.onResume();
        super.onResume();
    }

    @Override
    public void onDestroy() {
        // 退出时销毁定位
        mLocClient.stop();
        // 关闭定位图层
        mBaiduMap.setMyLocationEnabled(false);
        mMapView.onDestroy();
        mMapView = null;
        super.onDestroy();
    }

}
